import { useState, useCallback } from 'react';

// 生成唯一ID
const generateId = () => `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

export const useMessage = () => {
  const [messages, setMessages] = useState([]);

  const removeMessage = useCallback((id) => {
    setMessages(prev => prev.filter(msg => msg.id !== id));
  }, []);

  const addMessage = useCallback((message, type = 'info', options = {}) => {
    const id = generateId();
    const newMessage = {
      id,
      message,
      type,
      duration: options.duration || 3000,
      position: options.position || 'top-center',
      ...options
    };

    setMessages(prev => [...prev, newMessage]);

    // 如果设置了自动关闭时间，则自动移除
    if (newMessage.duration > 0) {
      setTimeout(() => {
        removeMessage(id);
      }, newMessage.duration);
    }

    return id;
  }, [removeMessage]);

  const clearMessages = useCallback(() => {
    setMessages([]);
  }, []);

  const clearMessagesByType = useCallback((type) => {
    setMessages(prev => prev.filter(msg => msg.type !== type));
  }, []);

  // 便捷方法
  const success = useCallback((message, options = {}) => {
    if (options.clearPrevious) {
      clearMessagesByType('success');
    }
    return addMessage(message, 'success', options);
  }, [addMessage, clearMessagesByType]);
  
  const error = useCallback((message, options = {}) => {
    if (options.clearPrevious) {
      clearMessagesByType('error');
    }
    return addMessage(message, 'error', options);
  }, [addMessage, clearMessagesByType]);
  
  const warning = useCallback((message, options = {}) => {
    if (options.clearPrevious) {
      clearMessagesByType('warning');
    }
    return addMessage(message, 'warning', options);
  }, [addMessage, clearMessagesByType]);
  
  const info = useCallback((message, options = {}) => {
    if (options.clearPrevious) {
      clearMessagesByType('info');
    }
    return addMessage(message, 'info', options);
  }, [addMessage, clearMessagesByType]);

  return {
    messages,
    addMessage,
    removeMessage,
    clearMessages,
    clearMessagesByType,
    success,
    error,
    warning,
    info
  };
};
